import {Node} from 'cc';
import {GameManager} from "db://assets/scripts/game/GameManager";
import {Utils} from "db://assets/scripts/utils/Utils";
import {MonsterController} from "db://assets/scripts/game/role/monster/MonsterController";

/**
 * 游戏获取怪物代理
 */
export class GameGetMonsterProxy {
    /**
     * 小怪、boss数组
     */
    private monsterNodes: Node[] = [];

    /**
     * 代理对象
     */
    private proxy: GameManager;

    constructor(proxy: GameManager) {
        this.proxy = proxy;
    }

    /**
     * 获取距离最近的小怪、boss节点
     * @returns
     */
    public getNearestMonster(): Node {
        // 当该层没有怪物时
        if (this.monsterNodes.length === 0) {
            return null;
        }

        // 按距离从近到远排序
        let arr = this.monsterNodes.sort((a: any, b: any) => {
            let distanceA = Utils.getTwoNodeXZLength(this.proxy.gamePlayerProxy.getPlayerNode(), a);
            let distanceB = Utils.getTwoNodeXZLength(this.proxy.gamePlayerProxy.getPlayerNode(), b);
            return distanceA - distanceB;
        })

        // 过滤掉已经死亡的怪物
        arr = arr.filter((item: Node) => {
            let monsterController = item.getComponent(MonsterController);
            return item.parent !== null && !monsterController.getIsDie();
        })

        // 返回第一个，也就是最近的一个
        return arr[0];
    }


    /**
     * 获取除了怪物本身自己外一定范围内的怪物
     *
     * @param monsterNode 怪物节点
     * @param isAll 是否需要全部
     * @param range 范围
     */
    public getNearbyMonster(monsterNode: Node, isAll: boolean = false, range: number = 7): Node[] {
        // 范围
        let monsterNodes = this.monsterNodes.filter((item: Node) => {
            let monsterController = item.getComponent(MonsterController);
            let length = Utils.getTwoNodeXZLength(this.proxy.gamePlayerProxy.getPlayerNode(), item);
            return item.parent !== null && !monsterController.getIsDie() && length <= range && monsterNode.worldPosition !== item.worldPosition;
        })

        // 当没有符合条件的怪物或需要全部怪物时
        if (monsterNodes.length === 0 || isAll) {
            // 返回该层级所有怪物
            return monsterNodes;
        }

        // 随机返回一个怪物
        let index = Math.floor(Math.random() * monsterNodes.length);
        return monsterNodes.filter((childNode: Node, idx: number) => {
            return idx === index;
        })
    }

    /**
     * 获取小怪、boss数组
     */
    public getMonsterNodes(): Node[] {
        return this.monsterNodes;
    }
}